import React, {useEffect, useRef, useState} from 'react';
import {Button, Tabs, message} from "antd";
import BlogText from "./component/BlogText";
import BlogContent from "./component/BlogContent";
import {addBlogText, getBlogTextListApi, editBlogApi} from "./AddBlogApi";
import {connect} from "react-redux";
import {setSpinning} from "../../store/actions/MyLoadingAction";
import {useNavigate, useSearchParams} from "react-router-dom";

function AddBlog(props) {
    const [panelNumber, setPanelNUmber] = useState("1")
    const refData = useRef()   // 博客信息
    const refData2 = useRef()  // 博客内容
    const Navigate = useNavigate()
    const [searchParams] = useSearchParams()
    const [messageApi, contextHolder] = message.useMessage();
    const [editBlog, setEditBlog] = useState({})
    let timerId = null
    // 切换tab
    const setPanelNUmberFun = async (index) => {
        if (index === '2') {
            if (!refData.current.imgUrl) {
                messageApi.warning('请选择博客封面')
                return
            }
            const isOk = await refData.current.verifyFormData()
            if (isOk) {
                setPanelNUmber(index)
            }
        } else {
            setPanelNUmber(index)

        }
    }

    // tab
    const items = [
        {
            key: '1',
            label: '博客信息',
            children: <BlogText editBlog={editBlog} ref={refData}/>,
        },
        {
            key: '2',
            label: '博客内容',
            children: <BlogContent editBlog={editBlog} ref={refData2}/>,
        },

    ];
    // 博客提交
    const submitData = () => {
        props.setSpinning(true)
        // 判断修改还是添加
        if (searchParams.has("id")) {
            // 编辑
            const reqData = {
                editId: searchParams.get('id'),
                blogCoverTitle: refData.current.blogTextData.blogCoverTitle,
                blogTypeId: refData.current.blogTextData.blogTypeId,
                blogTypeName: refData.current.blogTextData.blogTypeName,
                htmlText: refData2.current.htmlText,
                blogTitle: refData.current.blogTextData.title,
                blogUserId: props.blogUserId,
                blogCoverImage: refData.current.imgUrl
            }

            editBlogApi(reqData).then(res => {
                if (res.code === '200') {
                    messageApi.success('修改成功')
                    timerId = setTimeout(() => {
                        props.setSpinning(false)
                        Navigate('/HomeSystem/BlogContent')
                    }, 1000)
                } else {
                    messageApi.error('编辑失败')

                }
            }).catch(e => {
                props.setSpinning(false)
                messageApi.error('编辑失败')
            })
        } else {
            // 添加
            //格式化添加数据
            const data = {
                blogCoverTitle: refData.current.blogTextData.blogCoverTitle,
                blogTypeId: refData.current.blogTextData.blogTypeId,
                blogTypeName: refData.current.blogTextData.blogTypeName,
                blogCoverImage: refData.current.imgUrl,
                htmlText: refData2.current.htmlText,
                blogTitle: refData.current.blogTextData.title,
                blogUserId: props.blogUserId,
            }
            addBlogText(data).then(res => {
                if (res.code === '200') {
                    messageApi.success('添加成功')
                    timerId = setTimeout(() => {
                        props.setSpinning(false)
                        Navigate('/HomeSystem/BlogContent')
                    }, 1000)
                } else {
                    messageApi.error('添加失败')

                }
            }).catch(e => {
                props.setSpinning(false)
                messageApi.error('添加失败')
                console.log(e)
            })


        }

    }


    // 监听路由
    useEffect(() => {
        // 如果路由带id参数
        if (searchParams.has("id")) {
            const id = searchParams.get('id')
            const data = {
                listQuery: {
                    page: 1,
                    limit: 10
                },
                searchData: {
                    id: id
                }

            }
            getBlogTextListApi(data).then(res => {
                if (res.code === '200') {
                    setEditBlog(res.data.rows[0])
                }
            }).catch(e => {
                console.log(e)
            })
        }
        return () => {
            // 销毁定时器
            if (timerId) {
                clearTimeout(timerId)
            }
        }
    }, [])
    return (
        <div style={{position: "relative"}}>
            <Tabs defaultActiveKey="1" activeKey={panelNumber} items={items}/>
            <div style={{position: "absolute", right: '10px', top: '0px'}}>
                {
                    panelNumber === "1" ?
                        <Button type="primary" onClick={() => setPanelNUmberFun("2")}>下一步</Button> :
                        <Button type="primary" onClick={() => setPanelNUmberFun("1")}>上一步</Button>
                }
                <Button style={{marginLeft: 10}} type="primary" onClick={submitData}
                        disabled={panelNumber === '1' ? true : false}>提 交</Button>
            </div>
            {contextHolder}
        </div>
    );
}


const mapStoreToProps = (state) => {
    return {
        blogUserId: state.UserRedux.user.userNumber,
    }
}

const mapActionsToProps = {
    setSpinning
}

export default connect(mapStoreToProps, mapActionsToProps)(AddBlog);
